﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Git.Storage.WebApi.Common
{
    public class HttpHelper
    {
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string HttpPost(string Url, string postData)
        {
            byte[] dataArray = Encoding.GetEncoding("utf-8").GetBytes(postData);
            //创建请求           

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = dataArray.Length;
            request.ContentType = "application/json";
            //创建输入流
            Stream dataStream = null;
            //读取返回消息
            string res = string.Empty;
            try
            {
                dataStream = request.GetRequestStream();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dataStream != null)
            {
                //发送请求
                dataStream.Write(dataArray, 0, dataArray.Length);
                dataStream.Close();

                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                        res = reader.ReadToEnd();
                        reader.Close();
                    }
                }
            }
            return res;
        }
    }
}